package com.lm.service;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.lm.annotation.RedisLock;
import com.lm.enums.DistributedLockTypeEnum;
import com.lm.factory.DistributedLockFactory;
import com.lm.lock.RedisKeyEnum;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author LM
 * @date 2025/2/7 13:54
 */
@Service
@Slf4j
public class InventoryService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Value("${server.port}")
    private String port;

    private Lock lock = new ReentrantLock();

    @Resource
    private DistributedLockFactory distributedLockFactory;

    @Resource
    private RedissonClient redissonClient;

    /**
     * 单机版适用，分布式系统中jvm锁就会产生问题
     *
     * @return
     */
    public String sale() {
        String msg = "";
        lock.lock();
        try {
            String inventory = stringRedisTemplate.opsForValue().get("inventory");
            Integer inventoryNum = StrUtil.isNullOrUndefined(inventory) ? 0 : Integer.parseInt(inventory);
            if (inventoryNum > 0) {
                stringRedisTemplate.opsForValue().set("inventory", String.valueOf(--inventoryNum));
                msg = "成功卖出一个商品，库存剩余: " + inventoryNum;
                System.out.println(msg);
            } else {
                msg = "商品卖完了，o(╥﹏╥)o";
            }

        } finally {
            lock.unlock();
        }
        return msg + "\t" + "服务端口号：" + port;
    }

    /**
     * 分布式情况，简单实现
     * 判断、删除的操作不是原子性的，还是会产生问题
     *
     * @return
     */
    public String sale2() {
        String msg = "";
        String key = "zzyyRedisLock";
        String uuidValue = IdUtil.simpleUUID() + ":" + Thread.currentThread().getId();

        //采用自旋获取锁，并且加锁和过期时间设置为同一行，保证原子性
        while (Boolean.FALSE.equals(stringRedisTemplate.opsForValue().setIfAbsent(key, uuidValue, 30L, TimeUnit.SECONDS))) {
            //暂停毫秒
            try {
                TimeUnit.MILLISECONDS.sleep(20);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        try {
            String inventory = stringRedisTemplate.opsForValue().get("inventory");
            Integer inventoryNum = StrUtil.isNullOrUndefined(inventory) ? 0 : Integer.parseInt(inventory);
            if (inventoryNum > 0) {
                stringRedisTemplate.opsForValue().set("inventory", String.valueOf(--inventoryNum));
                msg = "成功卖出一个商品，库存剩余: " + inventoryNum;
                System.out.println(msg);
            } else {
                msg = "商品卖完了，o(╥﹏╥)o";
            }

        } finally {
            //判断加锁和解锁是同一次操作，只能删除自己的锁
            if (uuidValue.equals(stringRedisTemplate.opsForValue().get(key))) {
                stringRedisTemplate.delete(key);
            }
        }
        return msg + "\t" + "服务端口号：" + port;
    }

    /**
     * 加入lua脚本，保证删除原子性
     * 还存在锁可重入性问题
     *
     * @return
     */
    public String sale3() {
        String msg = "";
        String key = "zzyyRedisLock";
        String uuidValue = IdUtil.simpleUUID() + ":" + Thread.currentThread().getId();

        //采用自旋获取锁，并且加锁和过期时间设置为同一行，保证原子性
        while (Boolean.FALSE.equals(stringRedisTemplate.opsForValue().setIfAbsent(key, uuidValue, 30L, TimeUnit.SECONDS))) {
            //暂停毫秒
            try {
                TimeUnit.MILLISECONDS.sleep(20);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        try {
            String inventory = stringRedisTemplate.opsForValue().get("inventory");
            Integer inventoryNum = StrUtil.isNullOrUndefined(inventory) ? 0 : Integer.parseInt(inventory);
            if (inventoryNum > 0) {
                stringRedisTemplate.opsForValue().set("inventory", String.valueOf(--inventoryNum));
                msg = "成功卖出一个商品，库存剩余: " + inventoryNum;
                System.out.println(msg);
            } else {
                msg = "商品卖完了，o(╥﹏╥)o";
            }

        } finally {
            String luaScript =
                    "if (redis.call('get',KEYS[1]) == ARGV[1]) then " +
                       "return redis.call('del',KEYS[1]) " +
                    "else " +
                       "return 0 " +
                    "end";
            stringRedisTemplate.execute(new DefaultRedisScript<>(luaScript, Boolean.class), Collections.singletonList(key), uuidValue);
        }
        return msg + "\t" + "服务端口号：" + port;
    }

    /**
     * 可重入性redis分布式锁
     * @return
     */
    public String sale4() {
        String retMessage = "";
        Lock redisLock = distributedLockFactory.getDistributedLock(DistributedLockTypeEnum.REDIS.getType(), RedisKeyEnum.TEST.getKey());
        redisLock.lock();
        try
        {
            //1 查询库存信息
            String result = stringRedisTemplate.opsForValue().get("inventory");
            //2 判断库存是否足够
            Integer inventoryNumber = result == null ? 0 : Integer.parseInt(result);
            //3 扣减库存
            if(inventoryNumber > 0) {
                stringRedisTemplate.opsForValue().set("inventory",String.valueOf(--inventoryNumber));
                retMessage = "成功卖出一个商品，库存剩余: "+inventoryNumber+"\t";
                System.out.println(retMessage);
                //暂停几秒钟线程,为了测试自动续期
                try { TimeUnit.SECONDS.sleep(120); } catch (InterruptedException e) { e.printStackTrace(); }
                testReEnter();
            }else{
                retMessage = "商品卖完了，o(╥﹏╥)o";
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            redisLock.unlock();
        }
        return retMessage+"\t"+"服务端口号："+port;
    }

    /**
     * 可重入方法
     */
    private void testReEnter() {
        Lock redisLock = distributedLockFactory.getDistributedLock(DistributedLockTypeEnum.REDIS.getType(),RedisKeyEnum.TEST.getKey());
        redisLock.lock();
        try
        {
            System.out.println("################测试可重入锁#######");
        }finally {
            redisLock.unlock();
        }
    }

    /**
     * 使用Redisson锁
     * @return
     */
    public String saleByRedisson() {
        String msg = "";
        RLock redissonLock = redissonClient.getLock(RedisKeyEnum.TEST.getKey());
        redissonLock.lock();
        try
        {
            //1 查询库存信息
            String result = stringRedisTemplate.opsForValue().get("inventory");
            //2 判断库存是否足够
            Integer inventoryNumber = result == null ? 0 : Integer.parseInt(result);
            //3 扣减库存
            if(inventoryNumber > 0) {
                stringRedisTemplate.opsForValue().set("inventory",String.valueOf(--inventoryNumber));
                msg = "成功卖出一个商品，库存剩余: "+inventoryNumber;
                System.out.println(msg);
            }else{
                msg = "商品卖完了，o(╥﹏╥)o";
            }
        }finally {
            if(redissonLock.isLocked() && redissonLock.isHeldByCurrentThread()) {
                redissonLock.unlock();
            }
        }
        return msg+"\t"+"服务端口号："+port;
    }


    @RedisLock(value = "#id",keyType = RedisLock.KeyType.SPEL,waitTime = 3L,useMethodNameAsKeyPrefix =true)
    public String saleByRedisLock(Long id) {
        System.out.println("=====方法执行中");
        try {
            Thread.sleep(20000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        System.out.println("=====方法执行完成");
        return "测试成功";
    }
}
